package impl

import (
	"context"
	"gitee.com/kordar/bucket/form"
	"gitee.com/kordar/bucket/model"
	"gitee.com/kordar/bucket/vo"
	"gitee.com/kordar/goadmin/reader"
	"github.com/kordar/ginsys/resource"
	"github.com/kordar/gocrud"
	gocrudgorm "github.com/kordar/gocrud-gorm"
	"gorm.io/gorm"
)

type BucketServiceImpl struct {
	*gocrud.CommonResourceService
	db *gorm.DB
}

func NewBucketServiceImpl(db *gorm.DB) *BucketServiceImpl {
	return &BucketServiceImpl{db: db}
}

func (b *BucketServiceImpl) ResourceName() string {
	return "bucket"
}

func (b *BucketServiceImpl) GetBucket(id int64) (model.Bucket, error) {
	bucket := model.Bucket{}
	tx := b.db.Model(&bucket).Where("id = ?", id).First(&bucket)
	return bucket, tx.Error
}

func (b *BucketServiceImpl) SearchOne(body gocrud.SearchBody) gocrud.SearchOneVO {
	if body.Conditions == nil || len(body.Conditions) == 0 {
		return gocrud.NewSearchOneVO(map[string]string{})
	}
	searchBody := gocrudgorm.NewGormSearchBody(body)
	bucket := model.Bucket{}
	tx := searchBody.GormQuery(b.db, nil).First(&bucket)
	if tx.Error != nil {
		return gocrud.NewSearchOneVO(map[string]string{})
	}

	return gocrud.NewSearchOneVO(map[string]interface{}{
		"id":          bucket.ID,
		"name":        bucket.Name,
		"remark":      bucket.Remark,
		"config":      bucket.GetConfig(),
		"driver":      bucket.Driver,
		"create_time": bucket.CreateTime.Format("2006-01-02 15:04:05"),
		"update_time": bucket.UpdateTime.Format("2006-01-02 15:04:05"),
	})
}

func (b *BucketServiceImpl) Search(body gocrud.SearchBody) gocrud.SearchVO {
	searchBody := gocrudgorm.NewGormSearchBody(body)
	db := searchBody.GormQuery(b.db, nil).Model(&model.Bucket{})
	queryReader := reader.NewQueryReader(db, int(body.Page), int(body.PageSize))
	var bucketVOS []*vo.BucketVO
	return queryReader.SearchVO(&bucketVOS, nil)
}

func (b *BucketServiceImpl) Configs(ctx context.Context) map[string]interface{} {
	//locale := resp.GetLocale(ctx)
	return map[string]interface{}{
		"driver": []string{model.LocalDriver, model.CosDriver},
	}
}

func (b *BucketServiceImpl) Create(body gocrud.FormBody) (interface{}, error) {
	return resource.Create(body, b.db, &form.BucketForm{}, nil, nil)
}

func (b *BucketServiceImpl) Update(body gocrud.FormBody) (interface{}, error) {
	return resource.Updates(body, b.db, &form.BucketForm{}, nil, func(v interface{}) error {
		return nil
	})
}

func (b *BucketServiceImpl) Remove(body gocrud.RemoveBody) error {
	return body.Delete(&model.Bucket{}, b.db, nil)
}
